﻿/**
 *
 * @title: Basic MVC Framework, AbstractView Class
 * @author: Robert Turrall (http://www.robertturrall.com)
 * @license: Creative Commons Attribution 3.0 (http://creativecommons.org/licenses/by/3.0/)
 *			In other words: Please feel free to use, change, redistribute and do what you want with 
 *			this code. Just keep the original header and author attribution intact. Follow the license
 *			link for more info.
 * @updated: 31/12/2008
 *
 * @version	1.0 
 */

package net.turrall.mvc {

	import net.turrall.mvc.*;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.display.Sprite;
	
	/**
	 * Basic View class in Model/View/Controller triad.
	 */
	public class AbstractView extends Sprite implements View {
		
		private var _model:EventDispatcher;
		private var _controller:Controller;
		
		public function AbstractView(m:EventDispatcher, c:Controller) {
			// Set the model.
			setModel(m);
			// If a controller was supplied, use it. Otherwise let the first
			// call to getController() create the default controller.
			if (c !==null) {
				setController(c);
			}
		} 
		
		/**
		 * Returns the default controller for this view.
		 */
		public function defaultController(model:EventDispatcher):Controller {
			return null;
		}

		/**
		 * Sets the model this view is observing.
		 */
		public function setModel(m:EventDispatcher):void {
			model = m;
		}

		/**
		 * Returns the model this view is observing.
		 */
		public function getModel():EventDispatcher {
			return model;
		}

		/**
		 * Sets the controller for this view.
		 */
		public function setController(c:Controller):void {
			controller = c;
			getController(null).setView(this);
		}

		/**
		 * Returns this view's controller.
		 */
		public function getController(e:MouseEvent):Controller {
			// If a controller hasn't been defined yet...make one. 
			if (controller === null) {
				setController(defaultController(getModel()));
			}
			return controller;
		}

		/**
		 * An empty Observer update() method. 
		 * Subclasses of AbstractView will provide
		 * a concrete implementation for this method
		 * and update the view applicably
		 */
		public function update(e:CustomEvent):void {
			
		}
	}
}